<template>
    <div class="container">
        <page-header
         :backIconShow="true"
         :listIconShow="false"
         ></page-header>

         <list-tab
          :fieldData="fieldData"
         ></list-tab>

         <list-scroll-wrapper
          :courseData="courseData"
         ></list-scroll-wrapper>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

import { findItemIndex } from 'utils/tools'

import PageHeader from 'components/Header'
import ListTab from 'components/ListTab'
import ListScrollWrapper from 'components/ScrollWrapper/List'

import ListModel from 'models/list';

const listModel = new ListModel();

export default {
    name: 'ListPage',
    components: {
        PageHeader,
        ListTab,
        ListScrollWrapper
    },

    data () {
        return {
            fieldData: [],
            courseData: [],
            currentTabIndex: -1
        }
    },

    computed: {//计算属性
      ...mapState(['field', 'tabIndex']),
    },

    async mounted() {
        await this.getCourseFields();
        await this.getCourses(this.field);
        this.currentTabIndex = this.tabIndex;
        this.changeTabIndex(findItemIndex(this.fieldData, this.field) + 1);
    },

    activated () {
        if (this.currentTabIndex != this.tabIndex) {
            this.currentTabIndex = this.tabIndex;
            this.changeTabIndex(findItemIndex(this.fieldData, this.field) + 1);
        }
        
    },

    methods: {
        ...mapMutations(['changeTabIndex']),

        //方式一：这种方式比较繁琐
        // getCourseFields () {
        //     listModel.getCourseFields().then(res => {
        //         console.log(res);
        //     })
        // },

        //方式二：比方式一更好，代码更简洁
        async getCourseFields () {
            const data = await listModel.getCourseFields();
            this.fieldData = data.result;
            // console.log(data);
        },

        async getCourses (field) {
            const data = await listModel.getCourses(field);
            this.courseData = data.result;
            // console.log(data);
        }
    },

    watch: {
        field () {
            this.getCourses(this.field);
        }
    }
    
}
</script>

<style lang="scss" scoped>
  
</style>